<?php

namespace App\Http\Requests\Seller\GoodsType;

use App\Models\GoodsType;
use Illuminate\Foundation\Http\FormRequest;

class UpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => ['required', 'bail'],
            'parent_id' => ['required', function ($attribute, $value, $fail) {
                $goods_type = request()->route()->parameter('goods_type');
                $id = $goods_type->id;
                if($value==$id){
                    $fail(':attribute不能使自己');
                }
                $type = GoodsType::find($value);
                if($value!=0){
                    if(!$type){
                        $fail(':attribute是无效的');
                    }else if(!$type->is_parent){
                        $fail(':attribute是无效的');
                    }
                }
            }, 'bail'],
            'status' => ['required', 'boolean', 'bail'],
            'is_parent'=>['required','boolean',function($attribute,$value,$fail){
                $goods_type = request()->route()->parameter('goods_type');
                if(!$value&&$goods_type->children()->count()){
                    $fail(':attribute下有子分类，无法取消父类');

                }
                if($value&&$goods_type->goods()->count()){
                    $fail(':attribute下有商品，无法成为父级');
                }
            },'bail']

        ];
    }

    public function attributes()
    {
        return [
            'name' => '分类名称',
            'is_parent'=>'是否是父级'
        ];
    }

}
